package com.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.reggie.common.BaseContext;
import com.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//检查用户是否登录

@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

//    spring提供的路径匹配器,支持通配符
    public static final AntPathMatcher ANT_PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        String[] uris=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",  //移动端发送短信
                "/user/login" //移动端登录

        };
        log.info("拦截到请求{}",uri);
        boolean check = check(uris, uri);
        log.info("当前线程id{}",Thread.currentThread().getId());
//        如果 不需要拦截,直接放行
        if (check){
            log.info("本次请求不需要拦截{}",uri);
            filterChain.doFilter(request,response);
            return;
        }

//        判断登录状态,如果 已登录,则直接放行
        if (request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录,用户id为{}",request.getSession().getAttribute("employee"));

//            利用线程设置当前用户id
            long empId =(long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }

//   移动端判断是否登录
        if (request.getSession().getAttribute("user")!=null){
            log.info("用户已登录,用户id为{}",request.getSession().getAttribute("user"));

//            利用线程设置当前用户id
            long userId =(long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
   return;
    }

//    判断 请求是否需要拦截
    public boolean check(String[] uris,String requestURI){
        for (String uri : uris) {
            boolean match = ANT_PATH_MATCHER.match(uri, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
